<template>
    <div v-loading="loading" class="device-list-page">
        <!-- 页面标题栏 -->
        <div class="page-title">
            <el-button link class="back-btn" @click="handleBack">
                <el-icon>
                    <ArrowLeft />
                </el-icon>
            </el-button>
            <div class="title">设备列表</div>
        </div>

        <div class="content">
            <DeviceStatusCards :device-list="processedMeterList" @filter-status="handleStatusFilter" />

            <div class="filter-section">
                <div class="left-filters">
                    <!-- 搜索框 -->
                    <el-input v-model="filterForm.searchText" placeholder="搜索设备编号、位置..." prefix-icon="Search"
                        clearable />

                    <el-select v-model="filterForm.deviceStatus" placeholder="设备状态" clearable filterable>
                        <el-option label="全部状态" value="" />
                        <el-option label="在线" value="online" />
                        <el-option label="离线" value="offline" />
                        <el-option label="异常" value="error" />
                    </el-select>

                    <el-select v-model="filterForm.area" placeholder="区域" clearable filterable>
                        <el-option label="全部区域" value="" />
                        <el-option v-for="area in areaStore.areas" :key="area.id" :label="area.name" :value="area.id" />
                    </el-select>

                    <el-select v-model="filterForm.level" placeholder="表计等级" clearable filterable>
                        <el-option label="全部等级" value="" />
                        <el-option v-for="(_, index) in meterStore.meterLevels" :key="index + 1"
                            :label="`${index + 1}级`" :value="(index + 1).toString()" />
                    </el-select>
                </div>

                <div class="right-controls">
                    <el-select v-model="sortOption" placeholder="排序方式" style="width: 150px; margin-right: 16px;">
                        <el-option label="按状态排序" value="status" />
                        <el-option label="按表计等级排序" value="level" />
                    </el-select>

                    <el-button type="primary" class="add-device-btn" @click="handleAddDevice">
                        + 添加设备
                    </el-button>
                </div>
            </div>

            <!-- 空状态展示 -->
            <div v-if="filteredDeviceList.length === 0" class="empty-state">
                <el-empty description="没有找到符合条件的设备" :image-size="200">
                    <template #image>
                        <el-icon class="empty-icon">
                            <Monitor />
                        </el-icon>
                    </template>
                    <div class="mt-4 text-gray-500">
                        请尝试调整筛选条件
                    </div>
                </el-empty>
            </div>

            <!-- 设备列表区域 -->
            <div v-else class="device-list">
                <!-- 按状态排序 -->
                <template v-if="sortOption === 'status'">
                    <!-- 离线设备 -->
                    <div v-if="offlineDevices.length" class="device-group">
                        <h3 class="group-title">
                            <el-tag type="info" size="small">离线设备</el-tag>
                            <span class="device-count">{{ offlineDevices.length }}个</span>
                        </h3>
                        <div class="device-grid">
                            <div v-for="device in offlineDevices" :key="device.id" class="device-card">
                                <DeviceCard :device="device" :type="deviceType" />
                            </div>
                        </div>
                    </div>

                    <!-- 在线设备 -->
                    <div v-if="onlineDevices.length" class="device-group">
                        <h3 class="group-title">
                            <el-tag type="success" size="small">在线设备</el-tag>
                            <span class="device-count">{{ onlineDevices.length }}个</span>
                        </h3>
                        <div class="device-grid">
                            <div v-for="device in onlineDevices" :key="device.id" class="device-card">
                                <DeviceCard :device="device" :type="deviceType" />
                            </div>
                        </div>
                    </div>

                    <!-- 异常设备 -->
                    <div v-if="errorDevices.length" class="device-group">
                        <h3 class="group-title">
                            <el-tag type="danger" size="small">异常设备</el-tag>
                            <span class="device-count">{{ errorDevices.length }}个</span>
                        </h3>
                        <div class="device-grid">
                            <div v-for="device in errorDevices" :key="device.id" class="device-card">
                                <DeviceCard :device="device" :type="deviceType" />
                            </div>
                        </div>
                    </div>
                </template>

                <!-- 按等级排序 -->
                <template v-else>
                    <div v-for="(levelDevices, index) in filteredMeterLevels" :key="index" class="device-group"
                        v-show="levelDevices.length > 0">
                        <h3 class="group-title">
                            <el-tag type="primary" size="small">{{ index + 1 }}级表计</el-tag>
                            <span class="device-count">{{ levelDevices.length }}个</span>
                        </h3>
                        <div class="device-grid">
                            <div v-for="device in levelDevices" :key="device.meter_code" class="device-card">
                                <DeviceCard :device="{
                                    id: device.id,
                                    meter_code: device.meter_code,
                                    status: device.status === 1 ? 'online' : 'offline',
                                    area: areaStore.getAreaNameById(device.area_id) || '未知区域',
                                    location: device.installation_location || '位置未知',
                                    voltage: '220V',
                                    current: '5A',
                                    originalData: device
                                }" :type="deviceType" />
                            </div>
                        </div>
                    </div>
                </template>
            </div>
        </div>
        <el-dialog draggable :title="currentMeter ? '编辑表计' : '新增表计'" destroy-on-close align-center
            v-model="dialogVisible">
            <MeterDialog @success="refresh" @update:visible="dialogVisible = false" :pMeter="parent_meter"
                :id="currentMeter ? +currentMeter.meter_id : null" />
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { handleError } from '@/utils/handleError'
import { useRoute, useRouter } from 'vue-router'
import DeviceCard from './components/DeviceCard.vue'
import DeviceStatusCards from './components/DeviceStatusCards.vue'
import { useCompanyStore } from '@/stores/company'
import { useMeterStore } from "@/stores/meter"
import { useAreaStore } from "@/stores/area"

const route = useRoute()
const router = useRouter()
const deviceType = computed(() => Number(route.query.type) || 1)
const companyStore = useCompanyStore()
const meterStore = useMeterStore()
const areaStore = useAreaStore()
const dialogVisible = ref(false)
const parent_meter = ref(null)
const currentMeter = ref(null)
const handleAddDevice = () => {
    parent_meter.value = {
        id: null,
        label: "根节点",
        type: null,
    };
    currentMeter.value = null;
    meterStore.setCurrentSelectedType(deviceType);
    dialogVisible.value = true
}

// 处理状态卡片的点击筛选
const handleStatusFilter = (status) => {
    filterForm.deviceStatus = status
}

// 返回上一级
const handleBack = () => {
    router.back()
}

// 排序选项
const sortOption = ref('status')

// 筛选表单数据
const filterForm = reactive({
    deviceStatus: '',
    area: '',
    level: '',
    deviceType: '',
    searchText: ''  // 添加搜索文本
})

// 处理后的表计列表
const processedMeterList = ref([])

// 转换原始表计数据为设备列表格式
const processMeterData = (meters) => {
    // 定义状态映射
    const STATUS_MAP = {
        1: 'offline',  // 离线
        2: 'online', // 在线
        3: 'error'    // 异常
    }

    return meters.map(meter => ({
        id: meter.id,
        meter_code: meter.meter_code,
        status: STATUS_MAP[meter.status] || 'offline', // 使用状态映射，默认离线
        area: areaStore.getAreaNameById(meter.area_id) || '未知区域',
        areaId: meter.area_id,
        location: meter.installation_location || '位置未知',
        voltage: '220V',
        current: '5A',
        level: meter.standard_coal_factor || 1,
        originalData: meter
    }))
}

// 筛选后的设备列表
const filteredDeviceList = computed(() => {
    return processedMeterList.value.filter(device => {
        // 状态筛选
        if (filterForm.deviceStatus && device.status !== filterForm.deviceStatus) {
            return false
        }

        // 区域筛选
        if (filterForm.area && device.areaId !== filterForm.area) {
            return false
        }

        if (filterForm.level && !meterStore.meterLevels[filterForm.level - 1].map(meter => meter.id).includes(device.originalData.id)) {
            return false
        }

        // 搜索文本筛选（设备ID、位置等）
        if (filterForm.searchText) {
            const searchLower = filterForm.searchText.toLowerCase()
            return device.id.toLowerCase().includes(searchLower) ||
                device.location.toLowerCase().includes(searchLower) ||
                device.area.toLowerCase().includes(searchLower)
        }

        return true
    })
})

// 计算属性：按状态分组
const offlineDevices = computed(() =>
    filteredDeviceList.value.filter(device => device.status === 'offline')
)

const onlineDevices = computed(() =>
    filteredDeviceList.value.filter(device => device.status === 'online')
)

const errorDevices = computed(() =>
    filteredDeviceList.value.filter(device => device.status === 'error')
)

// 按等级分组的已筛选设备
const filteredMeterLevels = computed(() => {
    // 创建一个新数组来存储筛选后的每个等级的设备
    const levelsMap = meterStore.meterLevels.map((levelDevices, index) => {
        return levelDevices.filter(device => {
            const processedDevice = processMeterData([device])[0]
            // 应用筛选条件
            if (filterForm.deviceStatus &&
                processedDevice.status !== filterForm.deviceStatus) {
                return false
            }

            if (filterForm.area && device.area_id !== filterForm.area) {
                return false
            }

            if (filterForm.level && !meterStore.meterLevels[filterForm.level - 1].map(meter => meter.id).includes(device.id)) {
                return false
            }

            if (filterForm.searchText) {
                const searchLower = filterForm.searchText.toLowerCase()
                return device.meter_code.toLowerCase().includes(searchLower) ||
                    (device.installation_location || '').toLowerCase().includes(searchLower) ||
                    (areaStore.getAreaNameById(device.area_id) || '').toLowerCase().includes(searchLower)
            }

            return true
        })
    })

    return levelsMap
})
const loading = ref(false)
const refresh = async () => {
    if (!companyStore.currentCompany?.id) return
    loading.value = true
    try {
        // 获取当前公司下的所有表计
        await meterStore.fetchMeterList({
            type: deviceType.value,
            company_id: companyStore.currentCompany.id
        })
        // 获取并更新状态
        await meterStore.updateMeterStatus({
            id: companyStore.currentCompany.id
        });
        // 处理获取到的表计数据
        processedMeterList.value = processMeterData(meterStore.meterList)
    } catch (error) {
        handleError(error, "数据加载失败")
    } finally {
        loading.value = false
    }
}

watch([() => companyStore.currentCompany, () => deviceType], refresh, {
    immediate: true,
})
</script>

<style lang="scss" scoped>
.device-list-page {
    .page-title {
        display: flex;
        align-items: center;
        gap: var(--gap-small);
    }

    .content {
        padding: 0 var(--gap-normal);
    }

    .filter-section {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 24px;

        .left-filters {
            display: flex;
            gap: var(--gap-normal);
            align-items: center;


            :deep(.el-select) {
                width: 150px;
            }

            :deep(.el-input) {
                width: 200px;
            }

            .filter-trigger {
                cursor: pointer;
                font-size: 14px;

                i {
                    margin-right: 4px;
                }
            }
        }

        .right-controls {
            display: flex;
            gap: 16px;
            align-items: center;

            .add-device-btn {
                font-weight: 500;
            }
        }
    }

    .empty-state {
        display: flex;
        justify-content: center;
        align-items: center;
        min-height: 400px;
        margin-top: 40px;

        :deep(.el-empty) {
            .empty-icon {
                font-size: 100px;
                color: var(--color-primary);
                opacity: 0.5;
            }

            .el-empty__description {
                margin-top: 20px;
                font-size: var(--font-size-base);
                color: var(--color-text-secondary);
            }

            .el-button {
                margin-top: 20px;
            }
        }
    }

    .device-group {
        margin-bottom: 32px;

        .group-title {
            margin: 0 0 16px;
            display: flex;
            align-items: center;
            gap: var(--gap-small);

            .device-count {
                color: var(--color-text-primary);
                font-size: 14px;
                font-weight: normal;
            }
        }
    }

    .device-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: var(--gap-normal);
    }
}
</style>